// submit-report.js
const api = require('../../utils/api.js')

Page({
  data: {
    allocationId: '',
    taskInfo: null,
    formData: {
      quantity: '',
      work_hours: '',
      remark: ''
    },
    imageList: [],
    submitting: false
  },

  onLoad(options) {
    if (options.allocation_id) {
      this.setData({
        allocationId: options.allocation_id
      })
      this.loadTaskInfo()
    }
  },

  // 加载任务信息
  loadTaskInfo() {
    // 这里应该调用API获取任务详情
    // 暂时使用模拟数据
    this.setData({
      taskInfo: {
        id: this.data.allocationId,
        order: { order_no: 'ORD2024001' },
        model: { 
          product: { name: '测试产品' },
          name: '测试型号'
        },
        process: { name: '测试工序' },
        quantity: 100,
        work_type: 'piece'
      }
    })
  },

  // 数量输入
  onQuantityInput(e) {
    this.setData({
      'formData.quantity': e.detail.value
    })
  },

  // 工作小时输入
  onWorkHoursInput(e) {
    this.setData({
      'formData.work_hours': e.detail.value
    })
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      'formData.remark': e.detail.value
    })
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 9 - this.data.imageList.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          imageList: [...this.data.imageList, ...res.tempFilePaths]
        })
      }
    })
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      current: url,
      urls: this.data.imageList
    })
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const imageList = this.data.imageList
    imageList.splice(index, 1)
    this.setData({
      imageList: imageList
    })
  },

  // 提交报工
  submitReport() {
    const formData = this.data.formData
    const taskInfo = this.data.taskInfo

    // 验证表单
    if (taskInfo.work_type == 'piece' && !formData.quantity) {
      wx.showToast({
        title: '请输入完成数量',
        icon: 'none'
      })
      return
    }

    if (taskInfo.work_type == 'time' && !formData.work_hours) {
      wx.showToast({
        title: '请输入工作小时',
        icon: 'none'
      })
      return
    }

    this.setData({ submitting: true })

    // 提交报工数据
    const reportData = {
      allocation_id: this.data.allocationId,
      quantity: formData.quantity || 0,
      work_hours: formData.work_hours || 0,
      remark: formData.remark
    }

    api.submitReport(reportData).then(res => {
      // 上传图片
      if (this.data.imageList.length > 0) {
        this.uploadImages(res.data.id)
      } else {
        this.submitSuccess()
      }
    }).catch(err => {
      this.setData({ submitting: false })
      console.error('提交报工失败:', err)
    })
  },

  // 上传图片
  uploadImages(reportId) {
    const imageList = this.data.imageList
    let uploadedCount = 0
    let totalCount = imageList.length

    imageList.forEach((imagePath, index) => {
      api.uploadReportImage(reportId, imagePath).then(res => {
        uploadedCount++
        if (uploadedCount === totalCount) {
          this.submitSuccess()
        }
      }).catch(err => {
        console.error('上传图片失败:', err)
        uploadedCount++
        if (uploadedCount === totalCount) {
          this.submitSuccess()
        }
      })
    })
  },

  // 提交成功
  submitSuccess() {
    this.setData({ submitting: false })
    
    wx.showToast({
      title: '报工提交成功',
      icon: 'success'
    })

    setTimeout(() => {
      wx.navigateBack()
    }, 1500)
  }
}) 